# -*- coding: utf-8 -*-
"""
Flask 示例应用程序：用户注册、登录和电影个人收藏功能
"""
from flask import Flask, request, render_template_string, redirect, url_for, session
import requests  # 新增导入

app = Flask(__name__)
app.secret_key = 'your_secret_key'  # 用于会话管理


# 模型层（Model）
class User:
    def __init__(self, username, password):
        self.username = username
        self.password = password


class Movie:
    def __init__(self, title):
        self.title = title


# 数据访问层（DAO）
class UserDao:
    def __init__(self):
        self.users = {}
        # 添加初始用户
        self.add_user(User("chenzixuan", "846262"))

    def add_user(self, user):
        self.users[user.username] = user

    def get_user(self, username):
        return self.users.get(username)


class MovieDao:
    def __init__(self):
        self.movies = {}
        self.user_movie_collection = {}

    def add_movie(self, movie):
        self.movies[movie.title] = movie

    def get_movie(self, title):
        return self.movies.get(title)

    def add_to_collection(self, username, movie_title):
        if username not in self.user_movie_collection:
            self.user_movie_collection[username] = []
        if movie_title not in self.user_movie_collection[username]:
            self.user_movie_collection[username].append(movie_title)

    def remove_from_collection(self, username, movie_title):
        if username in self.user_movie_collection:
            if movie_title in self.user_movie_collection[username]:
                self.user_movie_collection[username].remove(movie_title)
                return True
        return False

    def get_collection(self, username):
        return self.user_movie_collection.get(username, [])


# 服务层（Service）
class UserService:
    def __init__(self, user_dao):
        self.user_dao = user_dao

    def register(self, username, password):
        if not username or not password:
            return False, "用户名和密码不能为空"
        if self.user_dao.get_user(username):
            return False, "用户名已存在"
        user = User(username, password)
        self.user_dao.add_user(user)
        return True, "注册成功"

    def login(self, username, password):
        user = self.user_dao.get_user(username)
        if user and user.password == password:
            return True, "登录成功"
        return False, "用户名或密码错误"


class MovieService:
    def __init__(self, movie_dao):
        self.movie_dao = movie_dao

    def add_movie(self, title):
        movie = Movie(title)
        self.movie_dao.add_movie(movie)

    def add_to_collection(self, username, movie_title):
        self.movie_dao.add_to_collection(username, movie_title)

    def remove_from_collection(self, username, movie_title):
        return self.movie_dao.remove_from_collection(username, movie_title)

    def get_collection(self, username):
        return self.movie_dao.get_collection(username)


# 初始化 DAO 和 Service
user_dao = UserDao()
movie_dao = MovieDao()
user_service = UserService(user_dao)
movie_service = MovieService(movie_dao)


def get_base_styles():
    return """
        <style>
            body {
                display: flex;
                justify-content: center;
                align-items: center;
                height: 100vh;
                margin: 0;
                flex-direction: column;
                font-family: Arial, sans-serif;
                background-color: #f5f5f5;
            }
            .container {
                text-align: center;
                padding: 30px;
                border: 1px solid #ddd;
                border-radius: 8px;
                box-shadow: 0 0 15px rgba(0,0,0,0.1);
                background-color: white;
                width: 350px;
            }
            input {
                margin: 10px 0;
                padding: 10px;
                width: 90%;
                border: 1px solid #ddd;
                border-radius: 4px;
            }
            button {
                padding: 10px 20px;
                margin: 15px 0;
                background-color: #4CAF50;
                color: white;
                border: none;
                border-radius: 4px;
                cursor: pointer;
                font-size: 16px;
            }
            button:hover {
                background-color: #45a049;
            }
            .delete-btn {
                background-color: #f44336;
                margin-left: 10px;
                padding: 5px 10px;
                font-size: 12px;
            }
            .delete-btn:hover {
                background-color: #d32f2f;
            }
            .search-btn {
                background-color: #2196F3;
                margin-left: 10px;
                padding: 5px 10px;
                font-size: 12px;
            }
            .search-btn:hover {
                background-color: #0b7dda;
            }
            a {
                color: #4CAF50;
                text-decoration: none;
                margin-top: 15px;
            }
            a:hover {
                text-decoration: underline;
            }
            .message {
                color: #d32f2f;
                margin: 10px 0;
            }
            ul {
                list-style-type: none;
                padding: 0;
                text-align: left;
            }
            li {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 8px;
                margin: 5px 0;
                background-color: #f9f9f9;
                border-radius: 4px;
            }
            .movie-item {
                flex-grow: 1;
            }
            .movie-info {
                margin-top: 20px;
                padding: 15px;
                background-color: #f0f8ff;
                border-radius: 5px;
                text-align: left;
            }
            .movie-poster {
                max-width: 100%;
                height: auto;
                margin-top: 10px;
            }
        </style>
    """


# 新增函数：搜索电影信息
def search_movie_info(title):
    # 使用OMDb API搜索电影信息
    api_key = 'your_omdb_api_key'  # 你需要去 http://www.omdbapi.com/ 申请一个免费的API key
    url = f"http://www.omdbapi.com/?t={title}&apikey={api_key}"

    try:
        response = requests.get(url)
        data = response.json()

        if data.get('Response') == 'True':
            return {
                'title': data.get('Title', title),
                'year': data.get('Year', '未知'),
                'plot': data.get('Plot', '暂无剧情简介'),
                'poster': data.get('Poster', ''),
                'director': data.get('Director', '未知'),
                'actors': data.get('Actors', '未知'),
                'rating': data.get('imdbRating', '未知')
            }
        else:
            return None
    except:
        return None


# 控制器层（Controller）
@app.route("/", methods=["GET"])
def home():
    return render_template_string("""
        <!DOCTYPE html>
        <html>
        <head>
            <title>电影收藏应用</title>
            """ + get_base_styles() + """
        </head>
        <body>
            <div class="container">
                <h1>欢迎来到电影收藏应用</h1>
                <a href="/register">注册</a>
                <span> | </span>
                <a href="/login">登录</a>
            </div>
        </body>
        </html>
    """)


@app.route("/register", methods=["GET", "POST"])
def register():
    message = ""
    if request.method == "POST":
        username = request.form.get("username")
        password = request.form.get("password")
        success, msg = user_service.register(username, password)
        if success:
            return render_template_string("""
                <!DOCTYPE html>
                <html>
                <head>
                    <title>注册成功</title>
                    """ + get_base_styles() + """
                </head>
                <body>
                    <div class="container">
                        <h2>注册成功!</h2>
                        <p>用户名: """ + username + """</p>
                        <a href="/">返回首页</a>
                    </div>
                </body>
                </html>
            """)
        message = msg

    return render_template_string("""
        <!DOCTYPE html>
        <html>
        <head>
            <title>注册</title>
            """ + get_base_styles() + """
        </head>
        <body>
            <div class="container">
                <h1>注册</h1>
                <div class="message">""" + message + """</div>
                <form action="/register" method="post">
                    <input name="username" placeholder="用户名" required>
                    <input name="password" type="password" placeholder="密码" required>
                    <button type="submit">注册</button>
                </form>
                <a href="/login">已有账号? 登录</a>
            </div>
        </body>
        </html>
    """)


@app.route("/login", methods=["GET", "POST"])
def login():
    message = ""
    if request.method == "POST":
        username = request.form.get("username")
        password = request.form.get("password")
        success, msg = user_service.login(username, password)
        if success:
            session['username'] = username
            return redirect(url_for("movie_collection"))
        message = msg

    return render_template_string("""
        <!DOCTYPE html>
        <html>
        <head>
            <title>登录</title>
            """ + get_base_styles() + """
        </head>
        <body>
            <div class="container">
                <h1>登录</h1>
                <div class="message">""" + message + """</div>
                <form action="/login" method="post">
                    <input name="username" placeholder="用户名" required>
                    <input name="password" type="password" placeholder="密码" required>
                    <button type="submit">登录</button>
                </form>
                <a href="/register">没有账号? 注册</a>
            </div>
        </body>
        </html>
    """)


@app.route("/movie_collection", methods=["GET", "POST"])
def movie_collection():
    if 'username' not in session:
        return redirect(url_for("login"))

    username = session['username']
    message = ""

    if request.method == "POST":
        if 'movie_title' in request.form:
            movie_title = request.form.get("movie_title")
            if movie_title:
                movie_service.add_to_collection(username, movie_title)
        elif 'delete_movie' in request.form:
            movie_title = request.form.get("delete_movie")
            if movie_service.remove_from_collection(username, movie_title):
                message = f"已成功删除电影: {movie_title}"
            else:
                message = f"删除电影失败: {movie_title}"

    collection = movie_service.get_collection(username)
    return render_template_string("""
        <!DOCTYPE html>
        <html>
        <head>
            <title>电影收藏</title>
            """ + get_base_styles() + """
            <style>
                .collection-container {
                    width: 450px;
                }
                .movie-list {
                    max-height: 300px;
                    overflow-y: auto;
                    margin: 15px 0;
                }
            </style>
        </head>
        <body>
            <div class="container collection-container">
                <h1>欢迎, """ + username + """!</h1>
                <h2>你的电影收藏</h2>
                """ + (f'<div class="message">{message}</div>' if message else "") + """
                <form action="/movie_collection" method="post">
                    <input name="movie_title" placeholder="添加电影标题" required>
                    <button type="submit">添加到收藏</button>
                </form>

                <div class="movie-list">
                    {% if collection %}
                    <ul>
                        {% for movie in collection %}
                            <li>
                                <span class="movie-item">{{ movie }}</span>
                                <div>
                                    <a href="/movie_info?title={{ movie }}" class="search-btn">查看详情</a>
                                    <form action="/movie_collection" method="post" style="display: inline;">
                                        <input type="hidden" name="delete_movie" value="{{ movie }}">
                                        <button type="submit" class="delete-btn">删除</button>
                                    </form>
                                </div>
                            </li>
                        {% endfor %}
                    </ul>
                    {% else %}
                    <p>你的收藏是空的。添加一些电影吧!</p>
                    {% endif %}
                </div>

                <a href="/logout">退出登录</a>
            </div>
        </body>
        </html>
    """, collection=collection)


# 新增路由：显示电影信息
@app.route("/movie_info", methods=["GET"])
def movie_info():
    if 'username' not in session:
        return redirect(url_for("login"))

    title = request.args.get("title")
    if not title:
        return redirect(url_for("movie_collection"))

    movie_data = search_movie_info(title)

    return render_template_string("""
        <!DOCTYPE html>
        <html>
        <head>
            <title>电影信息 - """ + title + """</title>
            """ + get_base_styles() + """
            <style>
                .info-container {
                    width: 500px;
                    text-align: left;
                }
                .back-btn {
                    display: block;
                    margin-top: 20px;
                }
            </style>
        </head>
        <body>
            <div class="container info-container">
                <h1>电影信息</h1>
                {% if movie_data %}
                <div class="movie-info">
                    <h2>{{ movie_data.title }} ({{ movie_data.year }})</h2>
                    <p><strong>导演:</strong> {{ movie_data.director }}</p>
                    <p><strong>演员:</strong> {{ movie_data.actors }}</p>
                    <p><strong>评分:</strong> {{ movie_data.rating }}/10</p>
                    <p><strong>剧情简介:</strong> {{ movie_data.plot }}</p>
                    {% if movie_data.poster %}
                    <img src="{{ movie_data.poster }}" alt="{{ movie_data.title }}海报" class="movie-poster">
                    {% endif %}
                </div>
                {% else %}
                <div class="message">
                    <p>无法获取电影"{{ title }}"的信息。请检查电影名称是否正确或稍后再试。</p>
                </div>
                {% endif %}
                <a href="/movie_collection" class="back-btn">返回收藏列表</a>
            </div>
        </body>
        </html>
    """, title=title, movie_data=movie_data)


@app.route("/logout")
def logout():
    session.pop('username', None)
    return redirect(url_for("home"))


if __name__ == "__main__":
    app.run(debug=True)